package com.car.rental.order.listener;

import com.car.rental.order.service.OrderService;
import com.car.rental.order.service.RentalPeriodService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import java.io.IOException;
import com.car.rental.order.config.RabbitMQConfig;

@Slf4j
@Component
@RequiredArgsConstructor
public class OrderMessageListener {

    private final OrderService orderService;
    private final RentalPeriodService rentalPeriodService;

    // 监听订单状态变更消息，处理订单的创建、支付、取消等状态变更
    @RabbitListener(queues = RabbitMQConfig.ORDER_STATUS_QUEUE)
    public void handleOrderStatusChange(String orderNo, Channel channel, Message message) {
        try {
            log.info("收到订单状态变更消息，订单号：{}", orderNo);
            // 处理订单状态变更逻辑
            
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                log.error("消息确认失败", ex);
            }
            log.error("处理订单状态变更消息失败", e);
        }
    }

    // 监听租期提醒消息，处理租期即将到期的提醒通知
    @RabbitListener(queues = RabbitMQConfig.RENTAL_REMINDER_QUEUE)
    public void handleRentalReminder(String orderNo, Channel channel, Message message) {
        try {
            log.info("收到租期提醒消息，订单号：{}", orderNo);
            rentalPeriodService.sendRentalReminder(orderNo);
            
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                log.error("消息确认失败", ex);
            }
            log.error("处理租期提醒消息失败", e);
        }
    }
} 